package cn.bouncyslime.algorithms.query;

//注意当整个数组长度为单数或者偶数带来的不同。
//折半查找，查找的前提是所列举的数组是已经排好序的
public class HalfQuery {
	public static void main(String[] args) {
		int low,mid,high;
		int flag = 88;
		int demo = 0;
//		int[] array = {5,13,19,21,37,56,64,75,80,88,92};
		int[] array = {5,13,19,21,37,40,56,64,75,80,88,92};
		
		low = 0;
		high = array.length-1;
		mid = (low+high)/2;
		while(low <= high) {
			//当要查找的数比中小时
			if(flag < array[mid]) {
				high = mid - 1;
				mid = (low+high)/2;
				demo ++;
			}else if(flag > array[mid]) {
				//当要查找的数比中大时
				low = mid + 1;
				mid = (low+high)/2;
				demo ++;
			}else if(flag == array[mid]) {
				//当要查找的数和中相等时，退出，得到结果
				demo ++;
				System.out.println("进行了"+demo+"次比较！");
				System.out.println("要查找的元素在数组中的："+mid+"位置！");
				break;
			}
		}
	}
}
